package com.lx.lib.activity;

import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.lx.commonlib.mvp.persenter.BasePresenter;
import com.lx.commonlib.mvp.view.activity.ToolbarActivity;
import com.lx.commonlib.utils.UIHandlerUtil;
import com.lx.lib.R;

public class UIHandlerActivity extends ToolbarActivity {
    private static final String TAG="xxx" +UIHandlerActivity.class.getSimpleName();

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_uihandler;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("UIHandlerUtil");

        TextView startThread = (TextView) findViewById(R.id.tv_start_child_thread);
        startThread.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for(int i=0;i<20;i++){
                            SystemClock.sleep(200);
                            Log.d(TAG,"i="+i);
                        }

                        UIHandlerUtil.getInstance().post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),"在UI线程Toast",Toast
                                        .LENGTH_SHORT).show();
                            }
                        });

                        Message message = new Message();
                        message.what=1000;
                        message.obj="哈哈哈哈";
                        UIHandlerUtil.getInstance().sendMessage(message);
                    }
                }).start();
            }
        });

        UIHandlerUtil.getInstance().setMessageListener(UIHandlerActivity.class.getSimpleName(),
                new UIHandlerUtil.MessageListener() {
                    @Override
                    public void handleMessage(Message msg) {
                        switch (msg.what){
                            case 1000:
                                String str = (String) msg.obj;
                                Toast.makeText(getApplicationContext(),str,Toast
                                        .LENGTH_SHORT).show();
                                UIHandlerUtil.getInstance().removeMessageListener(UIHandlerActivity.class.getSimpleName());
                                break;
                        }
                    }
                });
    }

}
